package com.pgcomb.poweriot.alarmservice.alarm;

import com.google.common.collect.Lists;
import com.pgcomb.common.bean.AlarmData;
import com.pgcomb.common.bean.ResultBean;
import com.pgcomb.common.enums.GlobalCodeEnum;
import com.pgcomb.poweriot.alarmservice.alarm.sendAlarm.EmailSender;
import com.pgcomb.poweriot.alarmservice.alarm.sendAlarm.SmsSender;
import com.pgcomb.poweriot.alarmservice.global.ErrorCodeException;
import com.pgcomb.web.dao.Contacts;
import com.pgcomb.web.dao.Equipment;
import com.pgcomb.web.dao.Room;
import com.pgcomb.web.repo.ContactsRepo;
import com.pgcomb.web.repo.EquipmentRepo;
import com.pgcomb.web.repo.RoomRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author zhengheqi
 * @version 1.0
 * @description: TODO
 * @date 2021/5/29 15:56
 */
@Slf4j
@Component
public abstract class CommonAlarmMessage implements AlarmMessage {
    @Resource
    private EquipmentRepo equipmentRepo;
    @Resource
    private ContactsRepo contactsRepo;
    @Resource
    private RoomRepo roomRepo;
    @Resource
    private EmailSender emailSender;
    @Resource
    private SmsSender smsSender;
    @Value("${alarm.notify-type.email}")
    private String isEmail;
    @Value("${alarm.notify-type.sms}")
    private String isSms;

    private static final String SMS_NOTIFY = "true";
    private static final String EMAIL_NOTIFY = "true";

    /**
     * 查询设备信息
     * @param sbId
     * @return
     */
    public Equipment getEquipment(String sbId) {
        //查询数据库中 设备信息
        Optional<Equipment> optionalEquipment = equipmentRepo.findById(sbId);
        if(!optionalEquipment.isPresent()){
            throw new ErrorCodeException(GlobalCodeEnum.MISSING_DB.getCode(), "Equipment is not exist sbId:" + sbId);
        }

        return optionalEquipment.get();
    }

    /**
     * 查询配电单元信息
     * @param roomId
     * @return
     */
    private Room getRoomInfo(Integer roomId) {
        Optional<Room> byId = roomRepo.findById(roomId);
        if(!byId.isPresent()){
            throw new ErrorCodeException(GlobalCodeEnum.MISSING_DB.getCode(), "Room is not exist roomId:" + roomId);
        }

        return byId.get();
    }

    /**
     * 查询联系人信息
     * @param contactsId
     * @return
     */
    public List<Contacts> getContacts(List<Integer> contactsId){
        if(CollectionUtils.isEmpty(contactsId)){
            throw new ErrorCodeException(GlobalCodeEnum.INVALID_PARAMS.getCode(), "参数异常");
        }

        // 查询数据库中 联系人信息
        Iterable<Contacts> allById = contactsRepo.findAllById(contactsId);

        ArrayList<Contacts> contacts1 = Lists.newArrayList(allById);
        if(CollectionUtils.isEmpty(contacts1)){
            throw new ErrorCodeException(GlobalCodeEnum.MISSING_DB.getCode(), "Contacts is not exist contactsIds:" + contactsId);
        }

        return contacts1;
    }

    protected abstract String getAlarmMessage(AlarmData alarmData) throws Exception;

    @Override
    public ResultBean<?> sendAlarmMessage(AlarmData alarmData) {
        try {

            //组织告警内容
            String message = getAlarmMessage(alarmData);

            Equipment equipment = getEquipment(alarmData.getSbId());
            List<Integer> contactsId = equipment.getContactsIds();
            List<Contacts> contacts = getContacts(contactsId);
            Room room = getRoomInfo(equipment.getRoomId());

            List<String> emailsTo = new ArrayList<>();
            List<String> smsTo = new ArrayList<>();

            if (CollectionUtils.isEmpty(contacts)) {
                return ResultBean.error("contacts is not exist");
            }
            contacts.forEach(contact -> {
                smsTo.add(contact.getContactsPhone());
                emailsTo.add(contact.getContactsMail());
            });

            //TODO send message
            //短信通知开关
            if(SMS_NOTIFY.equals(isSms)){
                smsSender.sendMsg(message, smsTo);
            }
            //邮件通知开关
            if(EMAIL_NOTIFY.equals(isEmail)){

                //邮件表格模板渲染
                String content = MessageFormat.format(EmailSender.loadEmailJobAlarmTemplate(),
                        room.getParkId(),
                        room.getRoomName(),
                        equipment.getEquipmentName(),
                        message);

                emailSender.sendMail(content, emailsTo);
            }

            //TODO 将通知信息入库

            return ResultBean.ok();
        } catch (Exception e) {
            log.error("", e);
            return ResultBean.error();
        }


    }
}
